package org.lucky.admin.service.impl;

import cn.hutool.jwt.JWTUtil;
import nl.bitwalker.useragentutils.UserAgent;
import org.apache.commons.codec.digest.DigestUtils;
import org.lucky.admin.util.RedisUtil;
import org.lucky_common.dto.AdminDto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author RTX 9090
 */
@Service("tokenService")
public class TokenService {
 
    @Resource
    private RedisUtil redisUtil;

    @Value("${token.key}")
    private String tokenKey;
 
    //生成token(格式为token:设备-加密的用户名-时间-六位随机数)
    public String generateToken(String userAgentStr, String username, Object o) {
        StringBuilder token = new StringBuilder("token:");
        //设备
        UserAgent userAgent = UserAgent.parseUserAgentString(userAgentStr);
        if (userAgent.getOperatingSystem().isMobileDevice()) {
            token.append("MOBILE-");
        } else {
            token.append("PC-");
        }
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put(username,o);
        // 生成token
        String relToken = JWTUtil.createToken(hashMap,tokenKey.getBytes());
        //加密的用户名
        token.append(DigestUtils.md5Hex(username)).append("-");
        //时间
        token.append(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())).append("-");
        //六位随机字符串
        token.append(new Random().nextInt(999999 - 111111 + 1) + 111111);
//        token.append("-"+relToken);
        System.out.println("token-->" + token.toString());
        return token.toString();
    }
 
    //把token存到redis中
    public void save(String token, AdminDto user) {
        if (token.startsWith("token:PC")) {
            redisUtil.setex(token, user, 2*60*60);
        } else {
            redisUtil.set(token, user,1800);
        }
    }

    public void saveUser(String username, AdminDto dto,String token) {
        if (token.startsWith("token:PC")) {
            redisUtil.setex(username, dto, 2*60*60);
        } else {
            redisUtil.set(username, dto,1800);
        }
    }
}